package utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import jdk.internal.org.objectweb.asm.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class JsonUtils {
    //创建对象映射器,转换JSON
    public static final ObjectMapper mapper = new ObjectMapper();
    //调用获取记录器方法
    public static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
    //将值写入字符串
    public static String toString(Object obj){
        if(obj == null){
            return null;
        }
        if(obj.getClass() == String.class){
            return (String) obj;
        }
        try {
            return  mapper.writeValueAsString(obj);
        } catch (IOException  e) {
            logger.error("json序列号出错:"+obj,e);
            return null;
        }
    }

    public static <T> T toBean(String json,Class<T> tClass){
        try {
            return mapper.readValue(json,tClass);
        } catch (IOException  e) {
            logger.error("json解析出错:"+json,e);
            return  null;
        }
    }

    public static <E> List<E> toList(String json,Class<E>eClass){
        try {
            return mapper.readValue(json,mapper.getTypeFactory().constructCollectionType(List.class,eClass));
        } catch (IOException  e) {
            logger.error("json解析出错：" + json, e);
            return null;
        }
    }

    public static <K,V> Map<K,V> toMap(String json,Class<K> kClass,Class<V> vClass){
        try {
            return mapper.readValue(json,mapper.getTypeFactory().constructMapType(Map.class,kClass,vClass));
        } catch (IOException e) {
            logger.error("json解析出错:"+json,e);
            return null;
        }
    }

}
